﻿using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace SMplusXTeam.SyncMoped.SyncGurke
{
    /// <summary>
    /// This class contains helper methods for handling the SyncFile-Database.
    /// </summary>
    public static class DbHelper
    {
        /// <summary>
        /// Inititalizes the database in the target directory.
        /// </summary>
        /// <param name="targetDirectory">The target directory.</param>
        public static void InititalizeDb(String targetDirectory)
        {
            if (String.IsNullOrEmpty(targetDirectory))
                throw new ArgumentNullException("targetDirectory");
            if (!Directory.Exists(targetDirectory))
                throw new ArgumentException("The following directory is not existing: " + targetDirectory);
            String fullWorkingDir = Path.Combine(targetDirectory, Config.WORKING_DIRECTORY);
            if (!Directory.Exists(fullWorkingDir))
                FileHelper.CreateHiddenFolder(fullWorkingDir);
            if (!File.Exists(Path.Combine(fullWorkingDir, Config.SYNC_FILE_DB_NAME)))
            {
                try
                {
                    SqlCeEngine engine = new SqlCeEngine(GetConnectionString(targetDirectory));
                    engine.CreateDatabase();
                    using (SqlCeConnection conn = new SqlCeConnection(GetConnectionString(targetDirectory)))
                    {
                        conn.Open();
                        SqlCeCommand cmd = conn.CreateCommand();
                        cmd.CommandText = @"
                            CREATE TABLE [SyncFiles] (
                                [Filename] nvarchar(4000)  NOT NULL,
                                [Modified] datetime  NOT NULL,
                                [Md5Sum] uniqueidentifier  NULL,
                                [LastRun] datetime  NOT NULL
                        );";
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = @"
                            ALTER TABLE [SyncFiles]
                                ADD CONSTRAINT [PK_SyncFiles]
                                PRIMARY KEY ([Filename] );";
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    TraceSource traceSource = new TraceSource(typeof(DbHelper).ToString());
                    traceSource.TraceEvent(TraceEventType.Error, 1, ex.Message);
                    traceSource.Close();
                    throw;
                }
            }
        }

        /// <summary>
        /// Generate the connection string for the SyncFile-Database.
        /// </summary>
        /// <param name="targetDirectory">The target directory.</param>
        /// <returns><see cref="String"/><para>The SQLCE-Connection-String</para></returns>
        public static String GetConnectionString(String targetDirectory)
        {
            if (String.IsNullOrEmpty(targetDirectory))
                throw new ArgumentNullException("targetDirectory");
            if (!Directory.Exists(targetDirectory))
                throw new ArgumentException("The following directory is not existing: " + targetDirectory);
            String fullWorkingDir = Path.Combine(targetDirectory, Config.WORKING_DIRECTORY);
            return @"Data Source='" + Path.Combine(fullWorkingDir, Config.SYNC_FILE_DB_NAME) + @"'";
        }

    }
}
